<template>
  <div class="center-wrapper">
    <!-- 地铁线路 -->
    <div id="subLine-controller">
      <div class="title-bg">
        <i class="iconfont metro-lineRoute"></i> 地铁线路
      </div>
      <div class="item-wrapper">
        <div
          class="item"
          v-for="(item, index) in subLineData"
          :key="index"
          @click.stop="handleItemClick(item)"
        >
          <div
            class="box"
            :style="{
              borderColor: item.color,
              backgroundColor: item.choosed ? item.color : 'rgba(0,0,0,0)',
            }"
          ></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name.slice(-3) }}</span>
        </div>
      </div>
    </div>
    <!-- 站点列表 -->
    <div id="station-controller">
      <div class="title-bg"><i class="iconfont metro-ditie"></i> 地铁站点</div>
      <div class="item-wrapper">
        <div class="item" :key="index" v-for="(item, index) in stationData">
          <div
            class="box"
            :style="{
              backgroundColor:
                index - 1 < metroIndex ? '#fff' : 'rgba(0,0,0,0)',
            }"
          ></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name }}</span>
        </div>
      </div>
    </div>
  </div>
  <popup-car
    v-if="isShowPopup"
    :attr="attr"
    :screenPosition="screenPosition"
    @close="isShowPopup = false"
  ></popup-car>
</template>

<script setup>
import { onBeforeUnmount, ref } from "vue";
import { storeToRefs } from "pinia";
import { useLineData } from "../store/index.js";
import { getSiteTimes, getPositions } from "../cesiumTools/core.js";
import SimpleLabel from "../cesiumTools/Bubble/htmlMarker.js";
import PopupCar from "../cesiumTools/Bubble/PopupCar.vue";
import { flyToDefaultView } from "../cesiumTools/course.js";

const { viewer } = useLineData();
const { lineData } = storeToRefs(useLineData());
//console.log(lineData);
const subLineData = ref([]);
subLineData.value = lineData.value.map((item) => {
  return { ...item, choosed: false };
});
console.log(subLineData.value);
const stationData = ref([]);
const metroIndex = ref(0); //当前选择的站线开始的站点索引
const currentLine = ref(null); //当前选择的站线
const screenPosition = ref({}); //气泡框位置
//气泡框
let options = { position: new Cesium.Cartesian3(0, 0, 0) };
const popupController = new SimpleLabel(viewer, options);
const removeCurrentRoute = () => {
  currentLine.value = null;
  isShowPopup.value = false;
  viewer.entities.remove(trainEntity);
};
const isShowPopup = ref(false);
const handleItemClick = async (item) => {
  // 如果点击的是同一个站线，返回
  if (currentLine.value?.name == item.name) return;
  removeCurrentRoute();
  /////需要做什么操作？1.移除之前站线 2.移除之前列车
  currentLine.value = item;
  // 点击站线，更新数据，渲染轨道列车，视角跳转，渲染popup
  const { stationsList, id } = item;
  // 控制ui
  subLineData.value.forEach((item) => {
    if (item.id == id) {
      item.choosed = true;
    } else {
      item.choosed = false;
    }
  });
  stationData.value = stationsList;
  // 从模拟服务端获取列车信息
  const trainInfo = await getTrainDataByLineId(id);
  // 渲染轨道列车
  renderTrain(trainInfo);
  // 渲染气泡框
  renderBubble(trainInfo);
  isShowPopup.value = true;
};
// 假设从服务端获取到列车的实时信息
const getTrainDataByLineId = (id) => {
  return new Promise((resolve, reject) => {
    // 构造一个随机的站点index
    let startIndex = 0;
    const startStationInfo = stationData.value[startIndex];
    const endStationInfo = stationData.value[startIndex + 1];
    // 由于站点坐标和路径坐标可能不会完全匹配，这里只是模拟数据，给列车虚构一个坐标点
    const trainData = {
      startIndex,
      currentPassengers: Math.ceil(Math.random() * 1000),
      startStation: startStationInfo,
      destination: endStationInfo,
      lineName: currentLine.value.name,
      currentSpeed: Math.ceil(Math.random() * 100),
      currentPosition: currentLine.value.paths[2],
    };
    resolve(trainData);
  });
};
let trainEntity;
// 渲染轨道列车
const renderTrain = (trainInfo) => {
  // 获取出发站点，得到metroIndex
  const { startIndex, currentPosition, currentSpeed } = trainInfo;
  metroIndex.value = startIndex;
  const pathIndex = currentLine.value.paths.findIndex(
    (path) => path === currentPosition
  );
  const { property, startTime, endTime } = handlePosition(
    currentSpeed,
    pathIndex
  );
  trainEntity = viewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: startTime,
        stop: endTime,
      }),
    ]),
    position: property,
    orientation: new Cesium.VelocityOrientationProperty(property),
    model: {
      scale: 0.17,
      uri: "/src/assets/model/metro.gltf",
      minimumPixelSize: 40,
    },
  });

  viewer.trackedEntity = trainEntity;
  viewer.clock.startTime = startTime.clone();
  viewer.clock.stopTime = endTime.clone();
  viewer.clock.currentTime = startTime.clone();
  // 监听时钟，如果列车到达站点，更新列车人数信息，并给一个暂停时间
  viewer.clock.onTick.addEventListener(tickEventHandler);
};

// 处理漫游效果，使用TimeIntervalCollection
const handlePosition = (speed, pathIndex) => {
  const property = new Cesium.SampledProperty(Cesium.Cartesian3);
  // 这里的时间可以自己定义
  let startTime = Cesium.JulianDate.fromDate(new Date());
  //通过速度计算最终时间
  const restPath = currentLine.value.paths.slice(
    pathIndex,
    currentLine.value.paths.length - 1
  );
  //转为Caterian3数组
  const positions = getPositions(restPath);
  //根据速度计算总时间和每段时间
  const { siteTimes, timeSum } = getSiteTimes(positions, speed);
  const endTime = Cesium.JulianDate.addSeconds(
    startTime,
    timeSum,
    new Cesium.JulianDate()
  );
  positions.forEach((position, index) => {
    const time = Cesium.JulianDate.addSeconds(
      startTime,
      siteTimes[index],
      new Cesium.JulianDate()
    );
    property.addSample(time, position);
  });
  return {
    property,
    startTime,
    endTime,
  };
};
// 当距离小于20米的时候，就可以给列车一个暂停
let apporachDistance = 20;
const tickEventHandler = () => {
  const startPosition = trainEntity.position.getValue(viewer.clock.currentTime);
  //通过当前的metroIndex和速度计算下一个站点的坐标
  const { position } = stationData.value[metroIndex.value + 1];
  const endPosition = new Cesium.Cartesian3.fromDegrees(
    position.lng,
    position.lat
  );
  let distance = Cesium.Cartesian3.distance(startPosition, endPosition);
  if (distance <= apporachDistance) {
    // 站点id变大，下一次计算的distance也会变大
    metroIndex.value++;
    // 将列车暂停
    viewer.clock.shouldAnimate = false;
    // 2s后恢复
    setTimeout(() => {
      viewer.clock.shouldAnimate = true;
    }, 2000);
  }
  // 还需要通过startPosition计算气泡框坐标
  popupController && popupController.changePosition(startPosition);
};

// 渲染气泡框
const attr = ref(null);
const renderBubble = (trainInfo) => {
  attr.value = {
    lineName: trainInfo.lineName,
    currentPassengers: trainInfo.currentPassengers,
  };
  console.log(attr.value);
  //获取气泡框位置
  const position = popupController.position;
  console.log(position);
  //转为屏幕坐标
  screenPosition.value = Cesium.SceneTransforms.wgs84ToWindowCoordinates(
    viewer.scene,
    position
  );
  console.log(screenPosition.value);
};
onBeforeUnmount(() => {
  removeCurrentRoute();
  //回到最初位置
  flyToDefaultView(viewer);
});
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
}

/* 地铁线路列表 */
#subLine-controller {
  position: absolute;
  bottom: 10%;
  left: 34%;
  transform: translateX(-50%);
  width: 180px;
  height: 200px;
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid #ab7818;
  display: flex;
  flex-direction: column;
}

.box {
  width: 10px;
  height: 10px;
  border-width: 1px;
  border-style: solid;
  background: transparent;
  user-select: all;
  cursor: pointer;
  transition: all 0.3s linear;
}

.item {
  width: 64.992px;
  height: 20.006px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0.156vw;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid #885f12;
  color: #fff;
  font-size: 0.521vw;
  pointer-events: all;
}

.item:hover {
  border: 1px solid #d8961a;
}

.item > span {
  line-height: 0.469vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 2.083vw;
}

.item > input {
  outline: none;
  border: none;
  transition: all 0.3s ease;
}

.item-wrapper {
  display: flex;
  justify-content: space-around;
  align-content: space-around;
  flex-wrap: wrap;
  flex: 1;
  padding: 4px;
  overflow: hidden;
}

/* 站点列表 */
#station-controller {
  width: 500px;
  height: 200px;
  border: 1px solid #ab7818;
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 40%;
  bottom: 10%;
  color: #fff;
  display: flex;
  flex-direction: column;
}

#station-controller .item-wrapper {
  justify-content: flex-start;
}

#station-controller .item {
  margin: 0 7px;
}

.title-bg {
  width: 100%;
  height: 30px;
  background: url("/src/assets/uiResources/title-bg.png");
  background-size: contain;
  color: #fff;
  background-repeat: no-repeat;
  line-height: 30px;
  margin-left: 10px;
  background: rgb(255, 255, 255);
  background-image: linear-gradient(
    180deg,
    rgba(255, 255, 255, 1) 9%,
    rgba(211, 156, 50, 1) 57%
  );
  /* -webkit-background-clip: text; */
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 站控措施图例 */
.right-wrapper {
  width: 11.417vw;
  height: 100%;
  position: absolute;
  right: 0px;
  top: 2.083vw;
}

.right-wrapper .query-item-title {
  cursor: default;
  pointer-events: none;
}

.right-wrapper .query-item-title::after {
  width: 20px;
  left: -20px;
}

.legend .query-item i {
  pointer-events: none;
  cursor: default;
}

.title {
  color: #fff;
}
</style>
